/*
	2019-02-20
	lane
*/
import config from "@/config/config.js"
let BaseUrl = config.baseUrl;

import store from "../../store/index.js"
function request(params, method) {
	let token = uni.getStorageSync("agent_token") || uni.getStorageSync("token") || '';
	
	// console.log('---------请求前 URL => ' + params.url + ' ---------')

	return new Promise(function(resolve, reject) {
		let URL = ''
		if (params.url.includes('http://') || params.url.includes('https://')) {
			URL = params.url;
		} else {
			URL = BaseUrl + params.url;
		}
		let header = {
			"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
			"Authorization": token,

			...params.header
		}
		// console.log('method=>', method)
		// console.log('header=>', header)
		// console.log('body=>', params.data)
		if(params.header&& params.header.token){
			header.Authorization = params.header.token
		}
		uni.request({
			url: URL,
			data: params.data,
			method: method,
			header: header,
			success(res) {
				// console.log( URL+'  接口响应=>',res)
				// console.log(res)
				// 成功回调
				
				if (res.statusCode == 200) {
					switch (res.data.code) {
						case 1:
							resolve(res.data)
							break;
						case -1:
							uni.showModal({
								title:'系统提示',
								content:res.data.msg,
								showCancel:false,
								success() {
									 
								}
							})
							
							reject(res)
							break;
						case 401:
							store.commit("account/removeToken")
							uni.showModal({
								title:'系统提示',
								content:res.data.msg,
								showCancel:false,
								success() {
									store.dispatch("account/loginByCode")
									// uni.clearStorageSync();
									// uni.reLaunch({
									// 	url:"/pages/hs-index/hs-index.vue"
									// })
								}
							})
						
							reject(res)
							break;
						case 500:
							uni.showToast({
								icon:'none',
								title:res.data.msg
							})
							reject(res)
							
							break;
						default:
							uni.showToast({
								icon:'none',
								title:res.data.msg
							})
							reject(res)
							break;
					}
					
				} else {
					switch (res.statusCode) {
						case 401:
							uni.showToast({
								title: '未登录或已过期',
								icon: 'none'
							})
							break;
						default:
							console.error(res);
							uni.showToast({
								icon: 'none',
								title: res.data.msg
							})
							reject(res)
							break;
					}
				}
			},
			fail(err) {
				// uni.hideLoading()
				uni.showToast({
					title: '服务器错误',
					icon: "none"
				})
				reject(err)
				// 失败回调
			},
			complete() {
				// uni.hideLoading()
				// 无论成功或失败 只要请求完成的 回调
			}
		})
	})
};
export default {

	get(params) {
		return request(params, "GET");
	},
	post(params) {
		return request(params, "POST")
	},
	put(params) {
		return request(params, "PUT")
	},

}
